<template>
  <div class="home">
    <ul>
      <li v-for="(item, index) in list" :key="index">
        <p>
          <span>{{ item.user }}</span>
          <span>{{ item.dateTime }}</span>
        </p>
        <p>消息：{{ item.msg }}</p>
      </li>
    </ul>
    <input type="text" v-model="msg" placeholder="请输入发送内容" />

    <button @click="handelSend">发送</button>
  </div>
</template>

<script>
export default {
  name: "home",
  data() {
    return {
      list: [],
      username: "",
      msg: "",
      socketPath: "ws://localhost:8000",
      socket: null,
    };
  },
  created() {
    this.init();
  },
  mounted() {
    this.username = localStorage.getItem("username");
    if (!this.username) {
      this.$router.push({
        path: "/login",
      });
      return;
    }
  },
  methods: {
    handelSend() {
      if (!this.msg.trim().length) {
        return;
      }
      this.socket.send(
        JSON.stringify({
          user: this.username,
          msg: this.msg,
          dateTime: new Date().getTime(),
        })
      );
      this.msg = "";
    },
    init() {
      let _this = this;
      if (typeof WebSocket === "undefined") {
        alert("您的浏览器不支持socket");
      } else {
        // 实例化socket
        _this.socket = new WebSocket(_this.socketPath);
        _this.socket.onopen = _this.open;
        _this.socket.onerror = _this.error;
        _this.socket.onclose = _this.close;
        _this.socket.onmessage = _this.message;
      }
    },
    open(e) {
      console.log("FE: WebSocket open", e);
    },
    error(e) {
      console.log("FE: WebSocket error", e);
    },
    close(e) {
      console.log("FE: WebSocket close", e);
    },
    message(e) {
      let _this = this;
      console.log("FE: WebSocket message", e);
      const reader = new FileReader();
      reader.readAsText(e.data, "utf-8");
      reader.onload = function () {
        const t = JSON.parse(reader.result);
        _this.list.push(t);
      };
    },
  },
};
</script>
